package com.lagou.edu.aspect;

import com.lagou.edu.configuration.SpringConfig;
import com.lagou.edu.utils.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TransactionAscept {

    @Pointcut("@annotation(com.lagou.edu.annotations.MyTransaction)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

        TransactionManager transactionManager = applicationContext.getBean(TransactionManager.class);

        try {
            transactionManager.beginTransaction();
            joinPoint.proceed();
            transactionManager.commit();
        } catch (Throwable throwable) {
            transactionManager.rollback();
            throwable.printStackTrace();

        }

    }
}
